import {Component, OnInit, ViewChild} from '@angular/core';
import {Washer} from '../../washers/shared/washer.model';
import {OrderService} from '../shared/order.service';
import {ActivatedRoute, Router} from '@angular/router';
import {Order} from '../shared/order.model';
import {MatSelectionList, MatSnackBar} from '@angular/material';

@Component({
  selector: 'app-order-detail',
  templateUrl: './order-detail.component.html',
  styleUrls: ['./order-detail.component.css']
})
export class OrderDetailComponent implements OnInit {

  public order: Order;
  public washers: Washer[] = [];
  public selectedWasherIds = [];

  public isEditingMode = false;
  constructor(
    private orderService: OrderService,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private snackBar: MatSnackBar) { }

  ngOnInit() {
    const orderId = this.activatedRoute.snapshot.paramMap.get('id');
    this.orderService.getOrderAvailableWashers(orderId).subscribe((value) => {
      this.washers = <Washer[]><any>value;
    }, (value) => {
      this.openSnackBar('获取可派单洗车工列表错误!', '');
    });
    this.orderService.getOrderDetail(orderId).subscribe((value) => {
      this.order = <Order><any>value;
    }, (value) => {
      this.openSnackBar('获取订单详情错误!', '');
    });
  }
  onEditClicked(target) {
    this.isEditingMode = true;
  }
  onAssignClicked(target) {
    this.orderService.assignOrder(String(this.order.orderId), this.order.orderNumber, this.selectedWasherIds).subscribe( result => {
      if (result) {
        alert('派单成功！' + this.selectedWasherIds.toString());
        this.router.navigate(['orders']);
      } else {
        alert('派单失败！');
      }
    });
  }
  onSaveClicked(target) {
    this.orderService.updateOrder(String(this.order.orderId), this.order).subscribe(value => {
        this.openSnackBar('更新成功！', '');
      },
      value => {
        this.openSnackBar('更新失败！', '');
      },
      () => {
        this.isEditingMode = false;
      });
  }
  onSelectionChanged(event) {
    if (event.option.selected) {
      event.source.deselectAll();
      event.option._setSelected(true);
      this.selectedWasherIds = [event.option.value];
    } else {
      this.selectedWasherIds = [];
    }
  }
  openSnackBar(message: string, action: string) {
    this.snackBar.open(message, action, {
      duration: 2000
    });
  }
}
